package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.wight.ChartView;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class MainActivity extends Activity {

    private TextView tv_type, tv_now_speed, tv_ave_speed;
    private Button btn;
    private ImageView needle;
    private Info info;
    private boolean flag;
    private int last_degree = 0;
    private ArrayList<ArrayList<String>> resultTotalList = new ArrayList<>();
    private int perCount = 0;
    private boolean isAgain;
    private int totalCount = 10;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x123) {
                tv_now_speed.setText(msg.arg1 + "KB/S");
                tv_ave_speed.setText(msg.arg2 + "KB/S");
                startAnimation(msg.arg1);
            }
            if (msg.what == 0x100) {
                tv_now_speed.setText("0KB/S");
                String result = tv_ave_speed.getText().toString();
                result = result.substring(0, result.indexOf("KB"));
                resultList.add(result);
                if (isAgain) {
                    resultTotalList.add(resultList);
                    isAgain = false;
                }
                chartView.refreshData(resultTotalList);
                perCount++;
                startAnimation(0);
                if (perCount < totalCount) {
                    startNetThread(500);
                } else {
                    btn.setText("开始测试");
                    btn.setEnabled(true);
                }
            }
            return false;
        }
    });

    private ArrayList<String> resultList = new ArrayList<>();
    //    private ListView resultListView;
//    private ResultAdapter resultAdapter;
    private TextView currentNetTypeTv;
    private ChartView chartView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        info = new Info();

        chartView = (ChartView) findViewById(R.id.result_chart_view);
        chartView.setXYLabels(
                new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "次"},   //X轴刻度
                new String[]{"", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "MB/S"},   //Y轴刻度
                "");

        tv_type = (TextView) findViewById(R.id.connection_type);
        currentNetTypeTv = (TextView) findViewById(R.id.current_nettype_tv);
        tv_now_speed = (TextView) findViewById(R.id.now_speed);
        tv_ave_speed = (TextView) findViewById(R.id.ave_speed);
        needle = (ImageView) findViewById(R.id.needle);
        btn = (Button) findViewById(R.id.start_btn);
//        resultListView = (ListView) findViewById(R.id.result_listview);
        Button clearButton = (Button) findViewById(R.id.clear_button);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultTotalList.clear();
                chartView.refreshData(resultTotalList);
//                if (resultAdapter != null) {
//                    resultAdapter.notifyDataSetChanged();
//                }
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                resultList = new ArrayList<>();
                perCount = 0;
                isAgain = true;
                startNetThread(0);
            }
        });

        findViewById(R.id.changtu_net_test_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ChangTuNetTestActivity.class));
            }
        });

        new AsyncTask<String, Integer, String>() {

            @Override
            protected String doInBackground(String... params) {
                return GetNetIp();
            }

            @Override
            protected void onPostExecute(String s) {
                if (s != null && !"".equals(s))
                    currentNetTypeTv.setText(s.substring(s.indexOf("(") + 1, s.length() - 1));
                super.onPostExecute(s);
            }
        }.execute();
    }

    private void startNetThread(int delay) {
        new AsyncTask<String, Integer, String>() {

            @Override
            protected String doInBackground(String... params) {
                int delay = Integer.parseInt(params[0]);
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                tv_type.setText(networkInfo.getTypeName());
                btn.setText("测试中");
                btn.setEnabled(false);
                info.hadfinishByte = 0;
                info.speed = 0;
                info.totalByte = 1024;
                new DownloadThread().start();
                new GetInfoThread().start();
                super.onPostExecute(s);
            }
        }.execute(String.valueOf(delay));
    }

    /**
     * 获取本机所连接的网络IP与地区信息
     *
     * @return 返回地区信息
     */
    public static String GetNetIp() {
        String IP;
        try {
            String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();

                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString = "";
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString + "\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    IP = data.getString("ip") + "("
//                            + data.getString("country")
//                            + data.getString("area") + "区"
                            + data.getString("region") + data.getString("city")
                            + data.getString("isp") + ")";

                    Log.e("提示", "您的IP地址是：" + IP);
                } else {
                    IP = "";
                    Log.e("提示", "IP接口异常，无法获取IP地址！");
                }
            } else {
                IP = "";
                Log.e("提示", "网络连接异常，无法获取IP地址！");
            }
        } catch (Exception e) {
            IP = "";
            Log.e("提示", "获取IP地址时出现异常，异常信息是：" + e.toString());
        }
        return IP;
    }

    class DownloadThread extends Thread {

        @Override
        public void run() {
            String url_string = "http://218.30.117.150/v1/0c69b881/7a574459.st3?t=22085030";
            long start_time, cur_time;
            URL url;
            URLConnection connection;
            InputStream iStream;
            try {
                url = new URL(url_string);
                connection = url.openConnection();
                info.totalByte = connection.getContentLength();
                iStream = connection.getInputStream();
                start_time = System.currentTimeMillis();
                byte[] buffer = new byte[64 * 1024];
                int len;
                while (!isOver && (len = iStream.read(buffer)) != -1 && flag) {
                    info.hadfinishByte += len;
                    cur_time = System.currentTimeMillis();
                    if (cur_time - start_time == 0) {
                        info.speed = 1000;
                    } else {
                        info.speed = info.hadfinishByte * 1000 / (cur_time - start_time);
                    }
                }
                iStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isOver;

    class GetInfoThread extends Thread {

        @Override
        public void run() {
            double sum, counter;
//            int cur_speed;
            int ave_speed;
            try {
                sum = 0;
                counter = 0;
                isOver = false;
                while (!isOver && info.hadfinishByte < info.totalByte && flag) {
                    Thread.sleep(1000);
                    sum += info.speed;
                    counter++;
//                    cur_speed = (int) info.speed;
                    ave_speed = (int) (sum / counter);
                    Message msg = new Message();
                    msg.arg1 = ((int) info.speed / 1024);
                    msg.arg2 = ave_speed / 1024;
                    msg.what = 0x123;
                    handler.sendMessage(msg);
                    if (counter >= 5) {
                        handler.sendEmptyMessage(0x100);
                        isOver = true;
                    }
                }
                if (info.hadfinishByte == info.totalByte && flag && !isOver) {
                    handler.sendEmptyMessage(0x100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putStringArrayList("result", resultList);
        outState.putSerializable("data", resultTotalList);
        super.onSaveInstanceState(outState);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.getSerializable("result") != null) {
            resultList = savedInstanceState.getStringArrayList("result");
        }
        if (savedInstanceState.getSerializable("data") != null) {
            resultTotalList = (ArrayList<ArrayList<String>>) savedInstanceState.getSerializable("data");
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onStop() {
        flag = false;
        info.hadfinishByte = 0;
        info.speed = 0;
        info.totalByte = 1024;
        startAnimation(0);
        btn.setText("开始测试");
        btn.setEnabled(true);
        super.onStop();
    }

    @Override
    protected void onResume() {
        flag = true;
        chartView.refreshData(resultTotalList);
        super.onResume();
    }

    private void startAnimation(int cur_speed) {
        int cur_degree = getDegree(cur_speed);

        RotateAnimation rotateAnimation = new RotateAnimation(last_degree, cur_degree, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(1000);
        last_degree = cur_degree;
        needle.startAnimation(rotateAnimation);
    }

    private int getDegree(double cur_speed) {
        int ret;
        if (cur_speed >= 0 && cur_speed <= 512) {
            ret = (int) (15.0 * cur_speed / 128.0);
        } else if (cur_speed >= 512 && cur_speed <= 1024) {
            ret = (int) (60 + 15.0 * (cur_speed - 512) / 256.0);
        } else if (cur_speed >= 1024 && cur_speed <= 5 * 1024) {
            ret = (int) (90 + 15.0 * (cur_speed - 1024) / 1024.0);
        } else if (cur_speed >= 5 * 1024 && cur_speed <= 10 * 1024) {
            ret = (int) (150 + 15.0 * (cur_speed - 5 * 1024) / 2.5 * 1024.0);
        } else {
            ret = 180;
        }
        return ret;
    }

    private long firstTime = 0;

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        String tempStr = "再按一次退出";
        if (firstTime == 0) {
            firstTime = System.currentTimeMillis();
            showToast(tempStr);
            return;
        }
        if ((System.currentTimeMillis() - firstTime) <= 2000) {
            super.onBackPressed();
        } else {
            firstTime = System.currentTimeMillis();
            showToast(tempStr);
        }
    }

    private void showToast(String string) {
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }
}
